package com.lhy.security.core;

import com.lhy.security.config.GSecurityConst;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

/**
 * 会话管理组件
 */
public class SSessionManager {

    /**
     * 获取当前登录的用户名
     * @return
     */
    public String getUsername(){
        return (String) getCurrentSession().getAttribute(GSecurityConst.LOGIN_USERNAME);
    }

    /**
     * 获取用户权限信息
     * @return
     */
    public HashSet<String> getPermission(){
        return (HashSet<String>) getCurrentSession().getAttribute(GSecurityConst.LOGIN_PERMISSIONS);
    }


    /**
     * 将登录状态保存在用户名中
     * @param userName
     * @param permission
     */
    public void saveUserInfo(String userName, HashSet<String> permission){
        HttpSession session = getCurrentSession();
        session.setAttribute(GSecurityConst.LOGIN_STATUS, true);
        session.setAttribute(GSecurityConst.SECURITY_SIGN, getSecuritySign(userName, permission.toString()));
        session.setAttribute(GSecurityConst.LOGIN_USERNAME, userName);
        session.setAttribute(GSecurityConst.LOGIN_PERMISSIONS,permission);
        session.setMaxInactiveInterval(GSecurityConst.SESSION_TIME);
    }

    /**
     * 注销会话信息
     */
    public void removeSession(){
        HttpSession httpSession = getCurrentSession();
        httpSession.invalidate();
    }

    /**
     * 安全签名校验
     * @return
     */
    public Boolean checkSecuritySign(){
        HttpSession httpSession = getCurrentSession();
        String userName = (String) httpSession.getAttribute(GSecurityConst.LOGIN_USERNAME);
        List<String> permission = (List<String>) httpSession.getAttribute(GSecurityConst.LOGIN_PERMISSIONS);
        String sign = (String) httpSession.getAttribute(GSecurityConst.SECURITY_SIGN);
        Objects.requireNonNull(sign, "[GzSecurity]数字签名验证失败");
        return sign.equals(getSecuritySign(userName, permission.toString()));
    }

    /**
     * 判断是否登录
     * @return
     */
    public Boolean isLogin(){
        HttpSession session = getCurrentSession();
        Boolean res = (Boolean) session.getAttribute(GSecurityConst.LOGIN_STATUS);
        return res != null && res;
    }

    /**
     * 获取数字签名
     * @return
     */
    public String getSecuritySign(String userName, String permission){
        return Arrays.toString(DigestUtils.md5Digest((userName+permission+GSecurityConst.MD5_SALT).getBytes()));
    }

    /**
     * 获取当前会话信息
     * @return
     */
    public HttpSession getCurrentSession(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getRequest().getSession();
    }


}
